
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Tan Le Anh
 */
public class Connect {
    String servername=null;
    String port=null;
    String database=null;
    String username=null;
    String password=null;
    
    public Connection dtConnect=null;
    
    public Connect(){
        servername = "localhost";
        port = "3306";
        database = "xpath";
        username = "root";
        password = "";
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            dtConnect=DriverManager.getConnection(getConnectionString());
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
    public Connect(String _server,String _database,String _user,String _pass){
        servername=_server;
        port="3306";
        database=_database;
        username=_user;
        password=_pass;
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            dtConnect=DriverManager.getConnection(getConnectionString());
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
    public String getConnectionString() throws Exception
    {   
        String kq="jdbc:mysql://";
        kq+=servername;
        kq+=":";
        kq+=port;
        kq+="/";
        kq+=database;
        kq+="?user=";
        kq+=username;
        kq+="&password=";
        kq+=password;
        kq+="&useUnicode=true&characterEncoding=utf8";
        return kq;
    }
    
     public void exec(String sql)
    {        
        try
        {
            java.sql.Statement query=dtConnect.createStatement();
            query.execute(sql);
        }
        catch(SQLException ex)
        {
            ex.printStackTrace();
        }        
    }
    
    public ResultSet execQuery(String sql)
    {
        ResultSet rs =null;
        try
        {
            java.sql.Statement query=dtConnect.createStatement();
            rs = query.executeQuery(sql);
        }
        catch(SQLException ex)
        {
            ex.printStackTrace();
        }
        return rs;
    }
    
    public void close() throws Exception{
        if(dtConnect!=null)
        {
            dtConnect.close();
        }
    }
}
